<template>
  <el-dialog
    :model-value="dialogVisible"
    width="700px"
    title="Excel导入"
    :before-close="dialogClose"
  >
    <el-form
      ref="formRef"
      :rules="rules"
      :model="ruleForm"
      label-position="“right”"
      label-width="155px"
    >
      <el-form-item label="模板下载:">
        <el-link @click="downloadTemplate" type="primary"
          >主机导入模板
        </el-link>
      </el-form-item>

      <el-form-item label="区域:" prop="region">
        <el-select
          class="m-2"
          v-model="ruleForm.region"
          @click="getRegions"
          placeholder="请选择"
        >
          <el-option
            v-for="item in regionsOptions"
            :key="item.id"
            :label="`${item.city}- ${item.region}`"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="连接方式: " prop="connect_type" required>
        <el-col :span="1.5">
          <el-tag size="large" type="info">IP</el-tag>
        </el-col>
        <el-col :span="7" :offset="1">
          <el-radio-group v-model="ruleForm.connect_type">
            <el-radio :label="1">公网</el-radio>
            <el-radio :label="2">内网</el-radio>
          </el-radio-group>
        </el-col>
      </el-form-item>

      <el-form-item label="关联SSH账号:" style="width: 100%" prop="ssh_id">
        <el-select
          style="width: 250px"
          v-model="ruleForm.ssh_id"
          filterable
          clearable
          @click="getsshs"
          placeholder="选择账号"
        >
          <el-option
            v-for="item in sshOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item>
        <!-- 
            auto-upload配置不主动上传,action可不填
            accept=".xlsx, .xls"限制了只能选择excel文件
            :http-request="uploadHttpRequest"是自定义上传方法
            :limit="1"限制选择一个文件
            :on-remove="handleRemove"文件列表移除文件时方法 
        -->

        <el-upload
          action=""
          accept=".xlsx, .xls"
          :auto-upload="false"
          :file-list="fileList"
          :limit="1"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :on-change="handleChange"
          :before-remove="beforeRemove"
          :on-exceed="handleExceed"
        >
          <el-button size="small" type="primary">选择文件</el-button>
          <template #tip>
          <div  class="el-upload__tip text-red">
            只能上传一个xls文件,且不超过10M
          </div>
            </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button type="primary" @click="submit" :disabled="uploadDisabled"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { getRegions } from "@/api/cloudPlatform/region";
import { getsshs } from "@/api/asset/ssh";
export default {
  name: "createExcel",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      ruleForm: {
        region: "",
        server_group: "",
        ssh_id: "",
        connect_type: 1, // 默认使用公网还是内网
      },
      rules: {
        region: [{ required: true, message: "请选择区域", trigger: "blur" }],
        server_group: [
          { required: true, message: "请选择主机分组", trigger: "blur" },
        ],
        ssh_id: [
          { required: true, message: "请选择关联登录账号", trigger: "blur" },
        ],
      },
      uploadDisabled: true,
      regionsOptions: "",
      groupOptions: "",
      fileList: [], // 空数组;上传文件的列表
      sshOptions: [],
      //   file: [],
    };
  },
  methods: {
    // 查询凭证
    getsshs() {
      getsshs().then((response) => {
        this.sshOptions = response.data.results;
        const passwd = [];
        for (let i in this.sshOptions) {
          passwd.push(
            this.sshOptions[i].name +
              "-" +
              this.sshOptions[i].authentication_type
          );
        }
        console.log("passwd 获取凭证:", passwd);
      });
    },
    // 点击预览
    handlePreview(file) {
      console.log("文件预览", file);
    },
    // 文件发生改变
    handleChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]];
        console.log("文件发生改变;this.fileList =", file.name, this.fileList);
        this.uploadDisabled = false;
      }
    },
    // 移除选择的文件
    handleRemove(file, fileList) {
      if (fileList.length < 1) {
        console.log("移除文件名:", file.name);
        this.uploadDisabled = true;
      }
    },
    // 定义超出限制时的行为
    handleExceed(files, fileList) {
      this.$message.warning(
        `超过最大上传数，共选择了 ${files.length + fileList.length} 个文件`
      );
    },

    beforeRemove(file) {
      let flag = this.$confirm(`确定移除 ${file.name}?`);
      console.log(flag);
      return this.$confirm(`确定移除 ${file.name}?`);
    },
    // 下载模版
    downloadTemplate() {
      this.$axios
        .get("/asset/excel/host/", {
          responseType: "blob",
        })
        .then((response) => {
          console.log(response);
          console.log("下载文件对象:", response);
          let blob = new Blob([response], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;",
          }); // 为blob设置文件类型，这里以.xls为例
          let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
          let a = document.createElement("a");
          a.href = url;
          a.download = "主机导入模版";
          a.click();
          // 释放这个临时的对象url
          window.URL.revokeObjectURL(url);
        });
    },
    // 自定义上传方法
    submit() {
      // 验证rules
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          let config = {
            headers: { "Content-Type": "multipart/form-data" }, //这里是重点，需要和后台沟通好请求头，Content-Type不一定是这个值
          };

          let formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
          formData.append("region", this.ruleForm.region);
          formData.append("server_group", this.ruleForm.server_group);
          formData.append("connect_type", this.ruleForm.connect_type);
          formData.append("ssh_id", this.ruleForm.ssh_id);
          formData.append("file", this.fileList[0].raw); //添加文件对象
          this.$axios
            .post("/asset/excel/host/", formData, config)
            .then((response) => {
              if (response.data.code == 20000) {
                console.log("response:", response);
                this.$message.success(response.data.detail);
                this.$parent.search(); // 调用父组件方法，更新数据
                //   this.$emit("search");
                this.dialogClose(); // 关闭窗口
                this.$emit("search");
              } else {
                this.$message.error(response.data.detail);
              }
            });
        } else {
          this.$message.error("格式错误！");
        }
      });
    },
    // 点击关闭，子组件通知父组件更新属性
    dialogClose() {
      console.log("子组件窗口关闭,通知父组件");
      this.$emit("close"); // 通知父组件

      //   this.$emit("update:visible", false); // 父组件必须使用v-model
    },
    // 获取区域数据
    getRegions() {
      getRegions(this.form).then((res) => {
        this.regionsOptions = res.data.results;
        const regions = [];
        for (let i in this.regionsOptions) {
          regions.push(this.regionsOptions[i].region);
        }
        console.log("regions 获取区域:", this.regionsOptions, regions);
      });
    },
  },
};
</script>